﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OAuth.Net.Common;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Configuration;

namespace NFAPI
{
    public class FileTokenStore : ITokenStore
    {
        #region ITokenStore Members

        public bool SaveTokens(string key, string userId, OAuth.Net.Common.IToken requestToken, OAuth.Net.Common.IToken accessToken)
        {
            StreamWriter sw = null;
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                sw = new StreamWriter(ConfigurationManager.AppSettings["tokenFile"], false);
                formatter.Serialize(sw.BaseStream, new TokenContainer { RequestToken = requestToken, AccessToken = accessToken, UserID = userId });
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (sw != null)
                {
                    sw.BaseStream.Close();
                }
            }
        }

        public bool GetTokens(string key, out string userId, out OAuth.Net.Common.IToken requestToken, out OAuth.Net.Common.IToken accessToken)
        {
            StreamReader sr = null;
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                sr = new StreamReader(ConfigurationManager.AppSettings["tokenFile"], false);
                TokenContainer tk = formatter.Deserialize(sr.BaseStream) as TokenContainer;
                requestToken = tk.RequestToken;
                accessToken = tk.AccessToken;
                userId = tk.UserID;
                return true;
            }
            catch {
                userId = null;
                requestToken = null;
                accessToken = null;
                return false;
            }
            finally
            {
                if (sr != null)
                {
                    sr.BaseStream.Close();
                }
            }
        }

        #endregion

        [Serializable]
        class TokenContainer
        {
            public IToken RequestToken { get; set; }
            public IToken AccessToken { get; set; }
            public string UserID { get; set; }
        }
    }
}
